<template>
  <div class="knowledge-base">
    <!-- Top Navigation -->
    <top-nav
      :username="username"
      v-model:is-dark="isDark"
    />

    <!-- Main Content -->
    <div class="main-content">
      <!-- Left Sidebar -->
      <knowledge-sidebar :username="username" />

      <!-- Content Area -->
      <div class="content">
        <!-- Header -->
        <div class="header">
          <div class="header-left">
            <h2>数据集</h2>
            <div class="sub-title">解析成功后才能问答哦。</div>
          </div>
          <div class="header-right">
            <el-input
              v-model="searchQuery"
              placeholder="搜索文件"
              :prefix-icon="Search"
              class="search-input"
            />
            <el-button type="primary" @click="showUploadDialog = true">
              + 新增文件
            </el-button>
          </div>
        </div>

        <!-- Batch Operations -->
        <div class="batch-operations">
          <el-dropdown @command="handleBatchCommand" :disabled="selection.length === 0">
            <el-button :disabled="selection.length === 0">
              批量操作 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="enable">
                  <el-icon><Select /></el-icon>
                  <span>启用</span>
                </el-dropdown-item>
                <el-dropdown-item command="disable">
                  <el-icon><Close /></el-icon>
                  <span>禁用</span>
                </el-dropdown-item>
                <el-dropdown-item command="analyze">
                  <el-icon><VideoPlay /></el-icon>
                  <span>解析</span>
                </el-dropdown-item>
                <el-dropdown-item command="cancel">
                  <el-icon><CircleClose /></el-icon>
                  <span>取消</span>
                </el-dropdown-item>
                <el-dropdown-item command="delete" divided>
                  <el-icon><Delete /></el-icon>
                  <span>删除</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <!-- Dataset Table -->
        <el-table 
          :data="filteredDatasets" 
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="名称" min-width="200" />
          <el-table-column prop="chunks" label="分块数" width="120" />
          <el-table-column prop="uploadDate" label="上传日期" width="180" />
          <el-table-column prop="splitMethod" label="切片方法" width="120" />
          <el-table-column prop="enabled" label="启用" width="100">
            <template #default="{ row }">
              <el-switch v-model="row.enabled" />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="解析状态" width="120">
            <template #default="{ row }">
              <el-tag 
                :type="row.status === '解析中' ? 'warning' : row.status === '未解析' ? 'info' : 'success'"
                :closable="row.status === '解析中'"
                @close="handleCancelAnalysis(row)"
              >
                {{ row.status }}
                <template v-if="row.status === '解析中'">
                  {{ row.progress }}%
                </template>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button-group>
                <el-button type="primary" link :disabled="row.status === '解析中'">
                  <el-icon><VideoPlay /></el-icon>
                </el-button>
                <el-button type="primary" link @click.stop="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button type="primary" link>
                  <el-icon><Delete /></el-icon>
                </el-button>
                <el-button type="primary" link>
                  <el-icon><Download /></el-icon>
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>

        <!-- Pagination -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next"
          />
        </div>
      </div>
    </div>

    <!-- Upload File Dialog -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传文件"
      width="50%"
      :close-on-click-modal="false"
    >
      <div class="upload-area">
        <el-upload
          class="upload-dragger"
          drag
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            点击或拖拽文件至此区域即可上传
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持单次或批量上传，本地即时的单次上传文件总大小上限为 1GB，
              单次批量上传文件数不超过 32，单个账户最大文件数量，对于
              demo.ragflow.io：每次上传的总文件大小不超过 10MB，每个文件不
              得超过 10MB，每个账户最多可上传 128 个文件，严禁上传违规文件。
            </div>
          </template>
        </el-upload>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showUploadDialog = false">取消</el-button>
          <el-button type="primary" @click="handleUpload">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Split Method Dialog -->
    <split-method-dialog
      v-model="showSplitMethodDialog"
      :initial-data="currentEditingData"
      @confirm="handleSplitMethodConfirm"
    />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { 
  Search, 
  Document,
  Notebook,
  ChatDotRound,
  Connection,
  Bell,
  QuestionFilled,
  Moon,
  Sunny,
  ArrowDown,
  Setting,
  VideoPlay,
  Edit,
  Delete,
  Download,
  UploadFilled,
  Select,
  Close,
  CircleClose
} from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import TopNav from '../components/TopNav.vue'
import KnowledgeSidebar from '../components/KnowledgeSidebar.vue'
import SplitMethodDialog from '../components/SplitMethodDialog.vue'

const router = useRouter()
const route = useRoute()

// Data
const username = ref('qinzhenlong')
const searchQuery = ref('')
const isDark = ref(false)
const showUploadDialog = ref(false)
const showSplitMethodDialog = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(1)
const selection = ref([])
const currentEditingData = ref(null)
const activeTopMenu = ref(route.path.split('/')[1])

// Mock data
const datasets = ref([
  {
    id: 1,
    name: '能监办大模型交流要点.docx',
    chunks: 0,
    uploadDate: '16/04/2025 12:57:28',
    splitMethod: 'General',
    enabled: true,
    status: '解析中',
    progress: 83
  }
])

// Computed
const filteredDatasets = computed(() => {
  if (!searchQuery.value) return datasets.value
  const query = searchQuery.value.toLowerCase()
  return datasets.value.filter(item => 
    item.name.toLowerCase().includes(query)
  )
})

// Methods
const handleMenuSelect = (index) => {
  activeTopMenu.value = index
}

const handleSelectionChange = (val) => {
  selection.value = val
}

const handleBatchCommand = (command) => {
  switch (command) {
    case 'enable':
      selection.value.forEach(item => item.enabled = true)
      break
    case 'disable':
      selection.value.forEach(item => item.enabled = false)
      break
    case 'analyze':
      selection.value.forEach(item => {
        item.status = '解析中'
        item.progress = 0
      })
      break
    case 'cancel':
      selection.value.forEach(item => {
        if (item.status === '解析中') {
          item.status = '未解析'
          item.progress = 0
        }
      })
      break
    case 'delete':
      // TODO: Implement batch delete
      break
  }
}

const handleFileChange = (file) => {
  console.log('File changed:', file)
  showSplitMethodDialog.value = true
}

const handleUpload = () => {
  // TODO: Implement upload logic
  showUploadDialog.value = false
}

const handleEdit = (row) => {
  currentEditingData.value = { ...row }
  showSplitMethodDialog.value = true
}

const handleSplitMethodConfirm = (formData) => {
  console.log('Split method settings:', formData)
  // TODO: Implement split method settings logic
}

const handleCancelAnalysis = (row) => {
  row.status = '未解析'
  row.progress = 0
}

const handleTopMenuSelect = (index) => {
  activeTopMenu.value = index
  router.push(`/${index}`)
}
</script>

<style scoped lang="scss">
.knowledge-base {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color-page);
}

.header {
  padding: 20px 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--el-border-color-light);
  background-color: var(--el-bg-color);

  .header-left {
    h2 {
      margin: 0;
      font-size: 24px;
      margin-bottom: 8px;
    }

    .sub-title {
      color: var(--el-text-color-secondary);
    }
  }

  .header-right {
    display: flex;
    gap: 16px;
    align-items: center;

    .search-input {
      width: 300px;
    }
  }
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: var(--el-bg-color);

  .batch-operations {
    margin-bottom: 16px;

    :deep(.el-dropdown-menu__item) {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .el-icon {
        margin-right: 0;
      }
    }
  }
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.upload-area {
  .upload-dragger {
    width: 100%;
  }

  .el-upload__tip {
    color: var(--el-text-color-secondary);
    font-size: 14px;
    line-height: 1.5;
    margin-top: 12px;
  }
}

:deep(.el-button-group) {
  .el-button {
    padding: 0 8px;
  }
}
</style>